﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using CoreEx.Common.Linq;

namespace CoreEx.Database.Linq
{
    public class TableSourceProvider : ExpressionVisitor
    {
        private IList<Expression> _expressions = new List<Expression>();
        private TranslateResult _translateResult;
        public TableSource GetTableSource(MemberExpression memberExpression, TranslateResult translateResult)
        {
            _translateResult = translateResult;
            Visit(memberExpression);
            return GetTableSource();
        }

        protected override Expression VisitMemberAccess(MemberExpression m)
        {
            _expressions.Add(m);
            return Visit(m.Expression);
        }

        protected override Expression VisitParameter(ParameterExpression p)
        {
            _expressions.Add(p);
            return base.VisitParameter(p);
        }

        
        private TableSource GetTableSource()
        {
            var joinSequence = _expressions.Reverse();
            foreach (var expression in joinSequence)
            {
                EnsureMemberIsJoined(expression);
            }

            return null;
        }

        private void EnsureMemberIsJoined(Expression expression)
        {            
            
            if (expression.NodeType == ExpressionType.Parameter)
                return;
            var memberExpression = (expression as MemberExpression);
            if (memberExpression != null)
            {
                if (_translateResult.TableSources.ContainsKey(memberExpression.Member))
                    return;
                var outerTableSource = GetOuterTableTableSource(memberExpression);
                var outerAlias = outerTableSource.Alias;
                var propertyMappingInfo = outerTableSource.MappedProperties[(PropertyInfo) memberExpression.Member];
                

            }


        }



        private TableSource GetOuterTableTableSource(MemberExpression memberExpression)
        {
            if (memberExpression.Expression.NodeType == ExpressionType.Parameter)
                return _translateResult.TableSources[memberExpression.Expression.Type];
            
            return _translateResult.TableSources[((MemberExpression) memberExpression.Expression).Member];            
        }
    }
}
